//
//  OAuthVIewController.swift
//  JJWeibo
//
//  Created by JJ on 15/9/1.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthVIewController: UIViewController,UIWebViewDelegate {
    
    private lazy var webView=UIWebView()
    
    override func loadView() {
        view=webView
        view.backgroundColor=UIColor.whiteColor()
        
        navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.loadRequest(NSURLRequest(URL: NetWorkTools.shareNetWorkTools.oathUrl))
        webView.delegate=self
        
    }
    
     func autoFill(){
        
        let js="document.getElementById('userId').value = 'zhaojj9043@gmail.com';" +
        "document.getElementById('passwd').value = 'zhaojianjun';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    @objc private func close(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString=request.URL!.absoluteString
        if !urlString.hasPrefix(NetWorkTools.shareNetWorkTools.redirect_uri)
        {
            return true
        }
        if let query=request.URL!.query where query.hasPrefix("code="){
        
            let code=query.substringFromIndex("code=".endIndex)
            
            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                   SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(JJSwitchRootViewControllerNotification, object: "JJ")
                    })
            })
           
        }else
        {
            self.close()
        }
        
        return false
    }

    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
   }
